package com.electronic.utils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: IFCA
 * @Description: 日期工具类
 */
public class DateTimeUtil {

    /**
     * 时间转换
     */
    public static LocalDateTime toLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    public static LocalDateTime convertPdfDateToLocalDateTime(String pdfDateString) {
        if (pdfDateString == null || pdfDateString.isEmpty()) {
            return null;
        }

        // 移除前缀 "D:"
        String dateStr = pdfDateString.startsWith("D:") ? pdfDateString.substring(2) : pdfDateString;

        // 解析日期时间部分
        String datePart = dateStr.substring(0, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime dateTime = LocalDateTime.parse(datePart, formatter);

        // 解析时区偏移
        Pattern pattern = Pattern.compile("([+-])?(\\d{2})'?(\\d{2})?'?");
        Matcher matcher = pattern.matcher(dateStr.substring(14));
        if (matcher.find()) {
            String sign = matcher.group(1);
            int hours = Integer.parseInt(matcher.group(2));
            int minutes = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;

            ZoneOffset offset = ZoneOffset.ofHoursMinutes(
                    sign != null && sign.equals("-") ? -hours : hours,
                    minutes);

            // 调整时区
            dateTime = dateTime.atOffset(offset).toLocalDateTime();
        }

        return dateTime;
    }
}


